/*
 * @Author: zhanggq
 * @Date: 2023-11-30 09:46:41
 * @LastEditors: zhanggq
 * @LastEditTime: 2023-11-30 09:46:42
 * @Description: 
 * @FilePath: /pemd/src/pemd/src/HPLCArchivesManager.cpp
 */

#include "../include/HPLCArchivesManager.h"
#include "../../../include/global_data_struct.h"

#include "CLogger.h"
#include <sys/types.h>
#include <sys/syscall.h> /*必须引用这个文件 */

HPLCArchivesManager::HPLCArchivesManager(std::shared_ptr<CConfigManager> cm, std::shared_ptr<HPLCProxy> hplc_ptr)
{
    m_cm = cm;
    m_hplc_ptr = hplc_ptr;
}
HPLCArchivesManager::~HPLCArchivesManager(){

}

void HPLCArchivesManager::ArchivesRegister()
{
    pthread_create(&m_pthread_id, NULL, handle_thread, this);
    pthread_join(m_pthread_id,NULL);

}

void *HPLCArchivesManager::handle_thread(void *arg){
    
    if (NULL == arg){
        return NULL;
    }
    pid_t tid = syscall(SYS_gettid);
    printf("HPLCArchivesManager::handle_thread------------------------------>threadid=%d\n", tid);

    HPLCArchivesManager *hm = (HPLCArchivesManager *)arg;
    sleep(1);  //延时1秒，与频点设置拉开


    const int rule_dlt645 = 2;
    std::list<std::string> lstAddrs;

    auto devs = hm->m_cm->get_terminal_devices();
    for (auto itd = devs->begin(); itd != devs->end(); itd++)
    {
        std::string devaddr = itd->second.slave_addr;

        auto itp = hm->m_cm->get_protocol_rule(itd->second.protocol_id);
        if (itp != nullptr)
        {
            //645协议 且承载通道为HPLC
            if ((itp->protocol_type == rule_dlt645) && (itd->second.com_type == PORT_TYPE_HPLC))
            {
                lstAddrs.push_back(devaddr);
            }
        }
    }
    
    if (0 < lstAddrs.size())
    {
        int rsplen = 0;
        char szstatus[64] = { 0 };
        hm->m_hplc_ptr->add_hplcarchives(lstAddrs, (uint8_t*)szstatus, rsplen);

        CLogger::getInstance()->LOG_I("hplc archives register,status=%s", szstatus);
    }
    else{
        CLogger::getInstance()->LOG_I("None hplc archives register");
    }

    return NULL;

}